<template>
    <div
        class="Derating"
        v-loading="pageLoading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <el-card class="box-card">
            <div slot="headerss" class="clearfix text_fl">
                <span>调额操作 --> 降额申请</span>
                <el-button class="btn_close" type="text" @click="handleClose">关闭</el-button>
            </div>
            <div>
                <div v-show="!CardSuccessInfo">
                    <el-form
                        ref="formData"
                        :rules="rules"
                        :inline="true"
                        :model="formData"
                        label-width="130px"
                        class="formData_form_inline"
                    >
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="账户类别:" class="text_fl">
                                        <el-select
                                            v-model="formData.CATEGORY"
                                            placeholder="请选择账户类别"
                                            @change="getCATEGORYObj"
                                            disabled
                                        >
                                            <el-option
                                                v-for="item in AccountionTYPE_INFO"
                                                :label="item.label"
                                                :value="item.code"
                                                :key="item.code"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="卡号:" class="text_fl" prop="CARDNO">
                                        <el-select
                                            v-model.trim="formData.CARDNO"
                                            placeholder="请选择卡号"
                                            @change="getCARDNBRFun"
                                            disabled
                                        >
                                            <el-option
                                                v-for="item in cardList_option"
                                                :label="item.CARDNBR"
                                                :value="item.CARDNBR"
                                                :key="item.CARDNBR"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <!-- <el-col :span="11" :offset="1">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="账户类别:" class="text_fl">
                                        <span class="el-form-item-span">{{formData.CATEGORY_filter}}</span>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="卡号:" class="text_fl">
                                        <span class="el-form-item-span">{{formData.CARDNO}}</span>
                                    </el-form-item>
                                </div>
                            </el-col>-->
                        </el-row>
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="信用额度:" class="text_fl">
                                        <span class="el-form-item-span">{{CREDITLIMIT}}</span>
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="12">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="可降至最低额度:" class="text_fl">
                                        <span class="el-form-item-span">{{MinmumAmount}}</span>
                                    </el-form-item>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="11" :offset="1">
                                <div class="text_center width30 dispy_in_bok">
                                    <el-form-item label="申请降至额度:" class="text_fl" prop="LOCLIMIT">
                                        <el-input v-model="formData.LOCLIMIT"></el-input>
                                    </el-form-item>
                                </div>
                            </el-col>
                        </el-row>
                        <!-- 话术 -->
                        <div class="hstable_wrap" v-if="speechList.length!=0">
                            <el-table
                                :data="speechList"
                                border
                                stripe
                                header-row-class-name="headerRow"
                                ref="showListTable"
                                class="heard-bg business_table hstable"
                                @selection-change="handleSelectionChange"
                            >
                                <el-table-column type="selection" label=" " min-width="55"></el-table-column>
                                <el-table-column label="业务话术">
                                    <template slot-scope="scope">{{scope.row.content}}</template>
                                </el-table-column>
                            </el-table>
                        </div>
                        <el-row>
                            <el-col :span="24" class="text_center">
                                <el-button type="primary" size="small" @click="handleClickbtn">申请</el-button>
                                <el-button
                                    type="primary"
                                    size="small"
                                    icon="el-icon-refresh-right"
                                    @click="handleClickRemove"
                                >重置</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div v-if="CardSuccessInfo">
                    <successInfoHint :CardSuccessInfo="CardSuccessInfo" pageTitle="降额申请"></successInfoHint>
                </div>
            </div>
            <el-dialog
                v-drag
                title="降额申请"
                :visible.sync="centerDialogVisible"
                width="500px"
                :append-to-body="true"
                top="30vh"
                :close-on-click-modal="false"
                center
            >
                <p>
                    卡号：
                    <span>{{formData.CARDNO}}</span>
                </p>
                <p>
                    卡产品：
                    <span>{{formData.CATEGORY_filter}}</span>
                </p>
                <p class="text_center padding_top15">
                    <span style="color:#3a8ee6; ">您确定对该卡号进行降额操作？</span>
                </p>
                <span slot="footer" class="dialog-footer">
                    <el-button
                        size="small"
                        icon="el-icon-circle-close"
                        @click="centerDialogVisible = false"
                    >取 消</el-button>
                    <el-button
                        type="primary"
                        size="small"
                        @click="submitFormReissueCard"
                        icon="el-icon-circle-check"
                    >确定</el-button>
                </span>
            </el-dialog>
        </el-card>
    </div>
</template>
<script>
import { mapGetters } from 'vuex';
import {
    closePage,
    getDictSelectList,
    itoStr,
    getDictMappingValue,
    getNewCardAccount3001,
    getCardInfo3004,
} from '@/utils/Common';

import successInfoHint from './components/successInfoHint'
export default {
    name: 'Derating',
    data() {
        const valitateRelflag = (rule, value, callback) => {
            console.log(this.CREDITLIMIT, 'this.CREDITLIMIT__信用额度');
            console.log(this.BALNCE, 'this.BALNCE_账面余额');
            console.log(this.MinmumAmount, 'this.MinmumAmount可降至最低额度');
            if (value < this.MinmumAmount * 1) {
                callback(new Error('申请降至额度，不能小于可降至最低额度'));
            } else if (value > this.CREDITLIMIT) {
                callback(new Error('申请降至额度，不能大于当前信用额度'));
            } else if (this.BALNCE !== 0 && value === this.MinmumAmount * 1) {
                callback(new Error('账户账面有欠款，最大降额金额不能降至0元'));
            } else {
                callback();
            }
        };
        return {
            formData: {
                CARDNO: '',
                CATEGORY: '',
                CATEGORY_filter: '',
                LOCLIMIT: '',
            },
            pageLoading: false,
            centerDialogVisible: false,
            DeratingSuccess: '',
            rules: {
                CARDNO: [{ required: true, message: '卡号不能为空！', trigger: 'blur' }],
                LOCLIMIT: [
                    { pattern: /^\d+$/, message: '请输入整数数字', trigger: 'blur' },
                    { required: true, message: '降额金额不能为空！', trigger: 'blur' },
                    { validator: valitateRelflag, trigger: 'blur', },
                    // {, message: '最大降额金额不能超过当前的永久额度', trigger: 'blur' }
                ],
            },
            BALNCE: '',//账面余额
            BALNCEFLG: '',//账面余额符号
            CREDITLIMIT: '',//信用额度
            MinmumAmount: '',//可降至最低额度
            CardSuccessInfo: '',//
            cardList_option: '',//当前账户下的所有的卡
            newCardInfo_3004: '',//
            newCardAccountInfo_3001: '',//
            speechList: [],//话术列表
            selectedList: [],
            MenuId: '',
        }
    },
    components: { successInfoHint, },
    computed: {
        ...mapGetters([
            'cardInfo_3004',
            'cardAccountInfo_3001',
            'cardList_3601',
            'defaultParams',
            'AccountionTYPE_INFO',
            'pinFlag',
            'isCurrentMenuInfo',
        ])
    },
    mounted() {
        this.MenuId = this.$route.params.id || '';
        this.setDefaultCardInfo();
        this.getDictValue();
        // console.log('this.cardAccountInfo_3001', this.cardAccountInfo_3001, this.cardAccountInfo_3001.CREDITLIMIT);
        this.getCardListOption(this.formData.CATEGORY);
    },
    methods: {
        // 修改默认卡
        setDefaultCardInfo() {
            // 这个方法只会调用一次
            this.pageLoading = true;
            if (!this.newCardInfo_3004) {
                this.newCardInfo_3004 = JSON.parse(JSON.stringify(this.cardInfo_3004));
            };
            if (!this.newCardAccountInfo_3001) {
                this.newCardAccountInfo_3001 = JSON.parse(JSON.stringify(this.cardAccountInfo_3001));
            };
            this.updated3004();
            this.getNewInfo();
        },
        updated3004() {
            // 每次 更换交易后 都需要执行这个方法
            this.formData.CARDNO = this.newCardInfo_3004.CARDNO;
            this.formData.CATEGORY = this.newCardInfo_3004.CATEGORY + '';
            this.formData.CARDNO = this.newCardInfo_3004.CARDNO;
            console.log('this.formData.CATEGORY', this.formData.CATEGORY);
        },
        getNewInfo() {
            this.BALNCE = this.newCardAccountInfo_3001.BALNCE;//账面余额
            this.BALNCEFLG = this.newCardAccountInfo_3001.BALNCEFLG; //账面余额 符号
            this.CREDITLIMIT = this.newCardAccountInfo_3001.CREDITLIMIT;//信用额度
            this.getviewInit();
        },
        // 页面初始化
        getviewInit() {
            console.log("账面余额_BALNCE", this.BALNCE);
            console.log('账面余额_BALNCE符号', this.BALNCEFLG);
            // 可降至最低额度（公式：账面余额+分期未分摊本金+分期未分摊手续费  MPBALS + MPBAL  MPBAX(手续费)
            let MPBAL_val = this.cardAccountInfo_3001.MPBAL;
            console.log('MPBAL————分期未分摊本金', this.newCardAccountInfo_3001.MPBAL);
            if (this.BALNCEFLG === '-') {
                const current = (this.BALNCE - MPBAL_val).toFixed(2);
                console.log('取绝对值', Math.abs(current));
                this.MinmumAmount = (current > 0) ? '0' : Math.abs(current);
            } else {
                this.MinmumAmount = (this.BALNCE + MPBAL_val).toFixed(2);
            }
            this.pageLoading = false;

        },
        async getDictValue() {
            this.formData.CATEGORY_filter = await getDictMappingValue('CATE', this.newCardInfo_3004.CATEGORY, this);
            await this.getspeechList();
        },
        //根据菜单id查询话术列表
        async getspeechList() {
            console.log("this.isCurrentMenuInfo.id", this.isCurrentMenuInfo.id);
            console.log("this.MenuId", this.MenuId);
            var checkParam = {
                'id': this.MenuId || this.isCurrentMenuInfo.id,
            };
            this.$post.busiMenu.getlistByMenuId(checkParam).then((res) => {
                console.log("话术查询结果：", res);
                if (res.status === 200) { // http通讯成功
                    if (res.data.status == 0) { // 业务请求成功
                        this.speechList = res.data.content;
                    }
                }
            });
        },
        handleSelectionChange(val) {
            this.selectedList = val;
        },
        /////////////////////////////////////////////////////////
        //获取当前账户类型下 所有的卡 
        getCardListOption(CATEGORY_val) {
            this.cardList_option = this.cardList_3601.filter((item) => (item.CATEGORY + '').trim() === CATEGORY_val);
            console.log(" this.cardList_option ", this.cardList_option);
        },
        // 获取账户类型
        getCATEGORYObj(val) {
            console.log('val', val);
            // 获取账户类型
            const pro = new Promise((resolve, reject) => {
                console.log(' this.AccountionTYPE_INFO', this.AccountionTYPE_INFO);
                this.AccountionTYPE_INFO.forEach(async (item) => {
                    console.log('item.code1', item.code);
                    if (item.code === val) {
                        console.log('item.code2', item.code);
                        this.CATEGORY_filter = item.label;
                        // 更新 newCardAccountInfo_3001
                        await getNewCardAccount3001(item.CARDNBR, this);
                        console.log('内部命令执行');
                        await resolve();
                    }
                });
            });
            pro.then(() => {
                console.log('执行2222');
                this.getCardListOption(val);
                this.getNewInfo();
                this.formData.CARDNO = '';
            })

        },
        // 选择 选中的需要操作的卡 后
        async getCARDNBRFun(cardNo) {
            this.pageLoading = true;
            // 选中 需要操作的卡后 需要重新跑 3004接口
            console.log("cardNo", cardNo);
            this.formData.CARDNO = cardNo;
            // 更新 newCardInfo_3004 里的值
            await getCardInfo3004(cardNo, this);
            await this.updated3004();
            // this.getNewInfo();
            this.pageLoading = false;
        },

        // 4001信用卡信用额度调整
        submitFormReissueCard() {
            const defaultParams = JSON.parse(JSON.stringify(this.defaultParams));

            let paramsval = {
                PINFLAG: this.pinFlag,
                SEVOPT: '12',//修改项目  12：禁止有卡消费
                CARDNBR: this.formData.CARDNO,
                CARDNO: this.formData.CARDNO,
                CHECKFLG: '100000000000000',//检查项目选择
                IDTYPE: this.newCardInfo_3004.KEYTYPE,//证件种类
                IDNO: this.newCardInfo_3004.CUSTID,//证件号码
                ADJOPT: '300',//额度调整方式
                LOPCT: '',//调整第一币种额度时上送
                FLAG: '-',//第一币种额度调整比例符号
                LOCLIMIT: this.formData.LOCLIMIT,//第一币种额度
                ADJBEG: '00000000',//临额生效日期 永久额度调整时送全0
                ADJEND: '00000000',//临额失效日期 永久额度调整时送全0
                CREDRSN: '13',//第一币种额度调整原因
                CUACFLG: '',//调整账户级/客户级额度标志 1：客户级  其它：账户级
                CASFLG: '1',//客户自助调整标志
                CAPCNTAFLG: '0',//是否调整预借现金比例标志 0 不调整
            }
            defaultParams.body.appBody = Object.assign(this.defaultParams.body.appBody, paramsval);
            defaultParams.body.appHead.tranCode = '4001';// 修改交易号
            console.log(defaultParams);
            this.$post.common.transPort(defaultParams).then(async (res) => {
                if (res.status === 200) { // 请求成功
                    const onelock = JSON.parse(res.data.jsonRes);
                    if (onelock.sysHead.rspCd == '000000') { // 交易成功
                        console.log(onelock, 'onelock');
                        this.CardSuccessInfo = onelock;
                        this.CardSuccessInfo.CATEGORY_filter = this.formData.CATEGORY_filter;
                        //更新3001 数据
                        await getNewCardAccount3001(this.formData.CARDNO, this);
                        // 更新缓存里的3001 数据
                        this.$store.commit('common/UPDATE_CARD_ACCOUNT_INFO', this.newCardAccountInfo_3001);

                    } else {
                        const ErrorMessage = `错误码：${onelock.sysHead.rspCd} ` + `错误信息：${onelock.sysHead.rspMsg}`;
                        this.$alert(ErrorMessage, onelock.sysHead.busiName, { customClass: 'error', type: 'error' });
                    }
                }
                this.centerDialogVisible = false; // 关闭弹框

            });
        },
        handleClickbtn() {
            this.$refs.formData.validate((valid) => {
                if (valid) {
                    console.log("this.selectedList.length", this.selectedList.length);
                    if (this.selectedList.length != this.speechList.length) {
                        this.$alert('话术尚未全部勾选！', '提示', {
                            customClass: 'warning', type: 'warning',
                        });
                        return;
                    }
                    this.centerDialogVisible = true;
                }
            });
        },
        // 重置 功能
        handleClickRemove() {
            this.formData.LOCLIMIT = '';
        },


        // 点击关闭
        handleClose() {
            closePage(this.$route, this, 1);
        },
    }
}
</script>
<style lang="scss">
.Derating {
    .el-card {
        border: none;
    }
    .butclass {
        position: absolute;
        margin-left: 20px;
    }
}
</style>